#!/usr/bin/env r
library(redux)
library(ggplot2)
library(grid)

drawClock <- function(hour, minute,date) {
  t <- seq(0, 2*pi, length=13)[-13]
  x <- cos(t)
  y <- sin(t)
  
  grid.newpage()
  pushViewport(dataViewport(x, y, gp=gpar(lwd=4)))
  # Circle with ticks
  grid.circle(x=0, y=-.1, default="native", 
              r=unit(0.9, "native"))
  grid.segments(.9*x, .9*y-.1, x*.81, y*.81-.1, default="native")
  # Hour hand
  hourAngle <- pi/2 - (hour + minute/60)/12*2*pi
  grid.segments(0, -.1, 
                .5*cos(hourAngle), .5*sin(hourAngle), 
                default="native", gp=gpar(lex=4))
  # Minute hand
  minuteAngle <- pi/2 - (minute)/60*2*pi
  grid.segments(0, -.1, 
                .7*cos(minuteAngle), .7*sin(minuteAngle), 
                default="native", gp=gpar(lex=2))    
  grid.circle(0, -.1, default="native", r=unit(.9, "mm"),
              gp=gpar(fill="white"))
  grid.text(date,y=0.95)
}

grabData <- function(topic){
  out<-NULL
  red_value<-ramqtt$GET(topic)
  if(!is.null(red_value)){
    sred<-strsplit(red_value,'\\+-')[[1]]
    if(length(sred)>1){
      out<-sum(as.numeric(strsplit(red_value,'\\+-')[[1]])*c(1,complex(real=0,imaginary=1)))
    }else{
      out<-as.numeric(sred)
    }
  }
  return(out)
}
ramqtt<-redux::hiredis(host="ramqtt")

png(filename = "/tmp/weather/clock.png",width = 240, height = 240, units = "px", pointsize = 12, bg = "white")
drawClock(hour=as.numeric(format(Sys.time(),"%H")),minute=as.numeric(format(Sys.time(),"%M")),date=format(Sys.time(),"%d.%m.%Y"))
dev.off()

dach=grabData('raw/ragps/w1_slave_temp/28-0416b3ead8ff/temperature')
carport=grabData('raw/rasolar/w1_slave_temp/28-0416b3e09aff/temperature')
wohnen=grabData('raw/radisplay/ee895/Temperature')

png(filename = "/tmp/weather/temperature.png",width = 560,height = 240, units = "px", pointsize = 12, bg = "white")
barplot(Re(c(dach,carport,wohnen)),horiz=TRUE,names=c("D","C","W"),xlim=c(0,30),col="black")
dev.off()

dach=grabData('raw/ragps/ee895/CO2')
carport=grabData('raw/ragarden/mh_z19/co2')
wohnen=grabData('raw/radisplay/ee895/CO2')

png(filename = "/tmp/weather/co2.png",width = 800, height = 240, units = "px", pointsize = 12, bg = "white")
barplot(Re(c(dach,carport,wohnen)),horiz=TRUE,names=c("D","C","W"),xlim=c(0,2000),col="black")
dev.off()
